package com.example.test.agent.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.test.agent.dto.LoginDTO;
import com.example.test.agent.dto.SaveUserDTO;
import com.example.test.agent.entity.BaseResult;
import com.example.test.agent.entity.User;
import com.example.test.agent.dao.UserDao;
import com.example.test.agent.service.UserService;
import com.example.test.shiro.jwt.JWTUtils;
import com.example.test.utils.MD5Util;
import com.example.test.utils.ProjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2021-04-29 21:15:23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;

    @Cacheable(cacheNames = {"userInfo"})
    @Override
    public BaseResult queryPage() {
        System.out.println("进入查询");
        List<User> userList = this.list();
        return BaseResult.success(userList);
    }

    /**
     * 添加用户信息
     * @param saveUserDTO
     * @return
     */
    @Override
    public BaseResult saveValue(SaveUserDTO saveUserDTO) {
        User user = (User) ProjectUtil.aCopyB(saveUserDTO, new User());
        user.setUserPassword(MD5Util.createPassword(user.getUserPassword()));
        boolean save = this.save(user);
        if(save){
            return BaseResult.successMsg("添加成功");
        }
        return BaseResult.error();
    }

    /**
     * 用户登陆
     * @param loginDTO
     * @return
     */
    @Override
    public BaseResult login(LoginDTO loginDTO) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_code", loginDTO.getUserCode());
        wrapper.eq("user_password", MD5Util.createPassword(loginDTO.getUserPassword()));
        User user = this.getOne(wrapper);
        if(user != null){
            String token = JWTUtils.createToken(user.getUserId(), "secret");
            return BaseResult.success(token);
        }
        return BaseResult.errorMsg("登陆失败");
    }


}
